package com.heima.aop;

import com.heima.annotaion.LogAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

//切面类
@Aspect
@Component
public class LogAspect {

    //定义切点路径,自定义的注解类路径
    @Pointcut("@annotation(com.heima.annotaion.LogAnnotation)")
    public void pointcut() {

    }
@Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //获取当前访问的类对象
    Class<?> className = pjp.getTarget().getClass();
    //获取当前访问的方法名
    String methodName = pjp.getSignature().getName();
    //获取方法的参数类型
    Class[] parameterTypes = ((MethodSignature) pjp.getSignature()).getParameterTypes();

    Method method = className.getMethod(methodName, parameterTypes);
    //获取方法上是否有注解
    if (method.isAnnotationPresent(LogAnnotation.class)) {
        //有的话，获取注解中的值
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        System.out.println("获取当前访问的类名"+className.getName());
        System.out.println("获取当前的方法名"+methodName);
        String type = annotation.type();
        System.out.println("获取注解中的值为"+type);
    }
    //执行代理方法
    Object proceed = pjp.proceed();
    return proceed;

}


}
